package com.dong.webtest;

/**
 * @author dengxiudong
 * @Date 2025/4/14 下午6:21
 */
import java.security.SecureRandom;

public class XorCrypto {

    // XOR加/解密（输入输出均为19位数字）
    public static String xorNumbers(String input, String key) {
        // if (input.length() !=19 || key.length() !=19)
        // throw new IllegalArgumentException("输入和密钥必须为19位");

        StringBuilder result = new StringBuilder();
        for (int i =0; i <input.length(); i++) {
            char cInput = input.charAt(i);
            char cKey = key.charAt(i);
            // ASCII码转换并确保结果为数字
            int encrypted = (cInput - '0') ^ (cKey - '0');
            result.append((char)(encrypted + '0'));
        }
        return result.toString();
    }

    //生成19位随机数字密钥
    public static String generateKey() {
        SecureRandom random = new SecureRandom();
        StringBuilder key = new StringBuilder();
        for (int i =0; i <19; i++) {
            key.append(random.nextInt(10));
        }
        return key.toString();
    }

    public static void main(String[] args) {
        // String original = "8634567890123456789"; //示例明文
        String original = "863456"; //示例明文
        System.out.println("明文：" + original);

        String key = "6892656989382719619"; //生成密钥
        System.out.println("密钥：" + key);

        String encrypted = xorNumbers(original, key); //加/解/密
        System.out.println("加/密后：" + encrypted);

        String decrypted = xorNumbers(encrypted, key); //解/密
        System.out.println("解/密后：" + decrypted);
    }
}

